package com.gitpull.utils;

import com.gitpull.pojo.gitInfo;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GitUtils {

    /**
     * getMatcher 正则表达式方法
     * @param regex
     * @param source
     * @return
     */
    public static String getMatcher(String regex, String source) {
        String str = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            str = matcher.group(1); // 只取第一组
        }
        return str;
    }


    /**
     * TokenClone 通过**连接克隆
     * @param repositoryUrl
     * @param privateToken
     * @param repositoryDir
     * @return
     * @throws InvalidRemoteException
     * @throws TransportException
     * @throws GitAPIException
     */
    public static Git TokenClone(String repositoryUrl, String privateToken, String repositoryDir)
            throws InvalidRemoteException, TransportException, GitAPIException {
        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN",
                privateToken);
        Git git = Git.cloneRepository().setCredentialsProvider(credentialsProvider).setURI(repositoryUrl)
                .setDirectory(new File(repositoryDir)).call();
        return git;
    }
/**
 * timestamp时间转换成String类型
 * */

   public static String timestampToString(int timestamp){
       Date date = new Date((long) timestamp * 1000);
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       return dateFormat.format(date);
   }
    /**
     * CredentialsProvider **认证
     * @param privateToken
     * @return
     * @throws InvalidRemoteException
     * @throws TransportException
     * @throws GitAPIException
     */
    public static CredentialsProvider Credentials(String privateToken)
            throws InvalidRemoteException, TransportException, GitAPIException {
        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN",
                privateToken);
        return credentialsProvider;
    }

    /**
     * LogRemote 获取Git远程仓库版本号
     * @param repositoryUrl
     * @param privateToken
     * @return
     * @throws IOException
     * @throws GitAPIException
     */
    public static List<gitInfo> LogRemote(String repositoryUrl, String privateToken, String studentNumber) throws IOException, GitAPIException {
        String temDir = ".//.//gitee//qw"; //临时文件夹
        if (new File(temDir).exists()) {
            temDir += "one";
        }
        Git git;
        List<gitInfo> gitInfos = new ArrayList<>();
        String versionID = "";
        git = TokenClone(repositoryUrl, privateToken, temDir);
        Iterable<RevCommit> iterable = git.log().call();
        for (RevCommit u : iterable) {
            int commitTime = u.getCommitTime();//提交时间
            gitInfo gitInfo = new gitInfo(studentNumber, timestampToString(commitTime), u.getName(), u.getAuthorIdent().getName(), u.getAuthorIdent().getEmailAddress());

            String name = u.getName();//版本号
            String anthor = u.getAuthorIdent().getName();//提交人姓名
            String emailAddress = u.getAuthorIdent().getEmailAddress();//提交人邮箱
            System.out.println(name);
            System.out.println(timestampToString(commitTime));
            System.out.println(anthor);
            System.out.println(emailAddress);
            gitInfos.add(gitInfo);


        }
        git.close();
        deleteFile(new File(temDir));
        return gitInfos;
    }


    /**
     * 获取Git本地仓库版本号
     *
     * @return versionID 版本号
     * @throws IOException
     * @throws GitAPIException
     */
    public static String Log(String repositoryDir) throws IOException, GitAPIException {
        String versionID = "";
        Repository localRepo;
        localRepo = new FileRepository(repositoryDir + "/.git");
        Git git = new Git(localRepo);
        System.out.println("获取本地");
        Iterable<RevCommit> iterable = git.log().all().call();
        for (RevCommit u : iterable) {
            //版本id
            String ID = String.valueOf(u.getId());
            versionID = getMatcher("commit\\s(\\w+)\\s?", ID);
            break;
        }
        git.close();
        return versionID;
    }

    /**
     * 删除目录以文件
     *
     * @param dirFile
     * @return
     */
    public static boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在，则退出
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {

            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }
        return dirFile.delete();
    }
}